package com.iiot.stream.tools;

import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;
import java.util.ListIterator;
import java.util.Properties;

import static java.sql.DriverManager.println;

/**
 * @author dzm
 * @create 2018-06-15-14:31
 */
public class ZookeeperClient {
    Logger logger = Logger.getLogger(ZookeeperClient.class);
    Properties prop = new Properties();
    public ZooKeeper getConfingFromZk(String host, int TimeOut){
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(host, TimeOut, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    logger.info("Already triggered " + event.getType() + " event !!!");
                }
            });
        } catch (Exception e){
            logger.error("zk lost");
        }
        return zk;
    }

    public void create(ZooKeeper zk,String path,String node,String data) throws KeeperException, InterruptedException {
        if (zk != null && path !=null && data !=null) {
            Stat stat = zk.exists(path, false);
            if (stat == null) {
                zk.create(path, node.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                zk.setData(path, Bytes.toBytes(data),-1);
                println(new String(zk.getData(path,false,null)));
            }else{
                logger.info(path+" is exists!!!");
                println(new String(zk.getData(path,false,null)));
            }
        }
    }

    public Properties getAll(ZooKeeper zk, String path) throws KeeperException, InterruptedException {

        if (zk != null) {
            // val prop = new Properties()
            try {
                Stat stat = zk.exists(path, false);
                if (stat != null) {
                    ListIterator<String> childrenIter = zk.getChildren(path, false).listIterator();
                    while(childrenIter.hasNext()){
                        String child = childrenIter.next();
                        String childPath = path;
                        if (!childPath.endsWith("/")) {
                            childPath = childPath + "/";
                        }

                        childPath = childPath + child;
                        byte[] buffer = zk.getData(childPath, true, stat);
                        if (buffer != null) {
                            String value = new String(buffer, StandardCharsets.UTF_8);
                            if (value != null) prop.setProperty(child.trim(), value.trim());
                        }
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return prop;
    }

}
